/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.ssau.logging;

import java.util.Date;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import ru.ssau.utils.JMSUtil;


@MessageDriven(mappedName="jms/logQueue", activationConfig={
    @ActivationConfigProperty(propertyName="acknowledgeMode", propertyValue="Auto-acknowledge"),
    @ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue")
})
public class EntityLoggerBean implements MessageListener {

    @PersistenceContext
    EntityManager entityManager;

    public EntityLoggerBean() {

    }

    public void onMessage(Message message) {
        if(!(message instanceof MapMessage)) {
            System.out.println("Unsupported message type. MapMessage required");
            return;
        }
        
        MapMessage mapMessage = (MapMessage) message;

        try {
            int entityId = mapMessage.getInt(JMSUtil.ENTITY_ID);
            String entityName = mapMessage.getString(JMSUtil.ENTITY_NAME);
            Date changeTime = new Date(mapMessage.getLong(JMSUtil.CHANGE_TIME));
            String action = mapMessage.getString(JMSUtil.PERFORMED_ACTION);

            LogRecord record = new LogRecord(entityId, changeTime, entityName, action);
            System.out.println("LogRecord: " + record.toString());
            entityManager.persist(record);
        } catch(JMSException ex) {
            System.out.println("Error in received message");
            ex.printStackTrace();
        }
    }
}
